<template>
  <div>
    <el-form
      ref="ruleForm"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item
        label="用户名"
        prop="username"
      >
        <el-input
          v-model="ruleForm.username"
          type="text"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item
        label="密码"
        prop="password"
      >
        <el-input
          v-model="ruleForm.password"
          type="password"
          autocomplete="off"
        />
      </el-form-item>
      <div>
        还没有账号 <a
          href="#"
          @click.prevent="toRegist"
        >用户注册</a>
      </div>
      <el-form-item>
        <el-button
          type="primary"
          @click="submitForm('ruleForm')"
        >
          登陆
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapActions } from 'vuex';

export default {
  data() {
    const validateUsername = (rule, value, callback) => {
      const reg = /^.*(?=.{6,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*? ]).*$/;
      if (!reg.test(value)) {
        callback(new Error('1个大写字母，1个小写字母，1个数字，1个特殊符号'));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        password: '',
        username: '',
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 6, message: '长度在6位以上', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '长度在6位以上', trigger: 'blur' },
          { validator: validateUsername, trigger: 'blur' },
        ],
      },
    };
  },
  methods: {
    ...mapActions(['login']),
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        console.log('valid: ', valid);
        if (valid) {
          //  发请求，登陆
          //  发送action
          const result = await this.login({
            username: this.ruleForm.username,
            password: this.ruleForm.password,
          });
          console.log(result);
          this.$router.push('/restaurant');
        }
        return false;
      });
    },
    toRegist() {
      this.$router.push('/regist');
    },
  },
};
</script>

<style lang="scss" scoped>

</style>
